<template>
	<div style="display: inline-block;">
		<!-- <el-button v-if="justButton" icon="el-icon-upload" type="primary" @click="handleClick"
            style="margin-left: 9px;">
            {{title}}
            <input type="file" accept="*/*" :multiple="max>1" ref="input" @change="fileChange" class="el-upload__input">
        </el-button> -->

		<template>
			<template v-if="!sysFileList">
				<div class="el-upload el-upload--text" @click="handleClick" v-if="fileList.length < max">
					<el-button v-if="fileList.length < max" icon="el-icon-upload" type="primary"
						style="margin-left: 9px;">
						<span>{{ title }}</span>
					</el-button>
					<input type="file" accept="*/*" :multiple="max > 1" ref="input" @change="fileChange"
						class="el-upload__input">
				</div>

				<ul class="el-upload-list el-upload-list--text" v-if="fileList.length > 0">
					<li class="el-upload-list__item is-ready" v-for="(item, $index) in fileList"
						style="font-size: 25px;" :key="$index" v-if="!!item.base64">
						<a class="el-upload-list__item-name">
							<i class="el-icon-document"></i>
							{{ item.fileName }}
						</a>
						<label class="el-upload-list__item-status-label">
							<i class="el-icon-upload-success el-icon-circle-check"></i>
						</label>
						<i class="el-icon-close" @click="handleRemove($index)" style="display: block;"></i>
					</li>
				</ul>
			</template>

			<template v-else>
				<el-upload ref="elUpload" class="upload-demo" :action="uploadUrl" :headers="headers"
					:file-list="elFileList" :multiple="max > 1" :on-success="onSuccess" :show-file-list="true">
					<el-button slot="trigger" size="small" type="primary">{{ title }}</el-button>
					<!--浏览文件-->
					<el-button icon="el-icon-view" type="primary" @click="exploreFile" style="margin-left: 9px;"
						v-if="!justButton && fileList.length < max">
						{{ sysFileListName }}
					</el-button>
				</el-upload>

				<ul class="el-upload-list el-upload-list--text" v-if="fileList.length > 0 && !justButton">
					<li class="el-upload-list__item is-ready" v-for="(item, $index) in fileList"
						style="font-size: 25px;" :key="$index" v-if="!!item.base64">
						<a class="el-upload-list__item-name">
							<i class="el-icon-document"></i>
							{{ item.fileName }}
						</a>
						<label class="el-upload-list__item-status-label">
							<i class="el-icon-upload-success el-icon-circle-check"></i>
						</label>
						<i class="el-icon-close" @click="handleRemove($index)" style="display: block;"></i>
					</li>
				</ul>

				<el-dialog :visible.sync="visible" :append-to-body="true" :modal-append-to-body="false"
					:title="sysFileListName" width="99%">
					<SysFileList :visibleChange="visible" :isChoice="true" :isChoiceMany="max > 1" :onlyImage="false"
						@choiceFileList="choiceFileList">
					</SysFileList>
				</el-dialog>
			</template>
		</template>
	</div>
</template>
<script>
import fileHelper from '@/common/components/fileHelper.js';
import common from '@/common/common.js';
import config from '@/common/config.js';
import SysFileList from "@/System/SysFileList";

export default {
	name: "uploadfile",
	components: {
		SysFileList
	},
	mixins: [common.baseVM],
	props: {
		max: {
			type: Number,
			default: 1
		},
		disabled: {
			type: Boolean,
			default: false
		},
		value: {
			type: String | Array
		},
		title: {
			type: String,
			default: '上传文件'
		},
		justButton: {
			type: Boolean,
			default: false
		},

		sysFileList: {
			type: Boolean,
			default: true
		},
		sysFileListName: {
			type: String,
			default: '浏览文件'
		}
	},
	computed: {
		fileResultList() {
			var arr = [];
			for (var i = 0; i < this.fileList.length; i++) {
				arr.push(this.fileList[i].base64);
			}
			return arr;
		},
		uploadUrl() {
			var r = config.webapiUrl + "/api/System/UploadFile";
			return r;
		},
		headers() {
			var key = config.tokenKey;
			var r = {};
			r[key] = this.$store.state.user.token;
			return r;
		}
	},
	watch: {
		value(n, old) { //外面的v-model值变化的时候,触发init方法
			// console.log("watch.value 外面的v-model值变化的时候,触发init方法");
			// console.log("watch.value new:", n);
			// console.log("watch.value old:", old);
			this.initFile(n, false);
		},
		fileList(n, old) {
			//this.$emit("change", n);
		}
	},
	data() {
		return {
			fileList: [],
			visible: false,

			elFileList: [],

			setTimeoutObj: null
		};
	},
	methods: {
		initFile(n, isAll) {
			if (n == null || n == "") {
				this.fileList = [];
				return;
			}
			var initFileList = () => {
				if (typeof n == "string") {
					this.fileList = [{
						fileName: fileHelper.getFileName(n),
						base64: n
					}];
					return;
				}
				var forMax = n.length > this.max ? this.max : n.length;
				var arr = [];
				for (var i = 0; i < forMax; i++) {
					var item = n[i];
					if (typeof (item) == "string") {
						arr.push({
							fileName: fileHelper.getFileName(item),
							base64: item
						});
					} else {
						arr.push(n);
					}
				}
				this.fileList = arr;
			};

			if (this.fileList == null || this.fileList.length == 0) {
				initFileList();
			}
			if (!isAll) return; //不是全部更新,就不管
			initFileList();
		},
		setFileList(arr) {
			var r = [];
			if (arr instanceof Array) {
				for (var i = 0; i < arr.length; i++) {
					var item = arr[i];
					r.push({
						fileName: this.getTheFileName(item),
						base64: item
					});
				}
			} else {
				r.push({
					fileName: this.getTheFileName(arr),
					base64: arr
				});
			}
			this.fileList = r;
		},
		choiceFileList(arr) {
			if (arr == null || arr.length == 0) return;
			var isArr = this.max > 1;
			if (isArr) {
				for (var i = 0; i < arr.length; i++) {
					var item = arr[i];
					this.fileList.push({
						fileName: item.fileName,
						base64: item.base64
					});
				}
			} else {
				this.fileList = [];
				var item = arr[0];
				this.fileList.push({
					fileName: item.fileName,
					base64: item.base64
				});
			}
			this.visible = false;
			this.setValue();
		},
		getTheFileName(item) {
			if (!item) return '';
			var index = item.lastIndexOf('/');
			if (index == -1) return fileHelper.getFileName(item);
			var r = item.substr(index + 1);
			return r;
		},
		setValue() {
			this.$emit("change", this.fileList);
			if (this.justButton) {
				this.fileList = [];
				return;
			}
			//console.log("setValue", this.fileResultList);
			if (this.max == 1) {
				this.$emit("input", this.fileResultList[0]);
				return;
			}
			this.$emit("input", this.fileResultList);
		},
		handleClick() {
			if (!this.disabled) {
				this.$refs.input.value = null;
				this.$refs.input.click();
			}
		},
		//上传文件
		fileChange(event) {
			//console.log(event);
			//console.log(event.target.files);
			// return;
			if (event.target.files.length == 0 || !event.target.files[0].size) return; //判断是否有文件数量
			var files = []; //重新弄个数组做为参数,是因为原来的数组不支持.map
			for (var i = 0; i < event.target.files.length; i++) {
				files.push(event.target.files[i]);
			}
			//console.log("files", files);
			this.addFileList(files); //获取files文件组传入处理
			event.target.value = '' //清空val值，以便可以重复添加一张文件
		},
		addFileList(files) {
			var total = this.fileList.length + files.length;
			if (this.max != 1) { //只有一个的情况,覆盖掉
				if (total > this.max) {
					var tempFiles = [];
					var hasCount = this.max - this.fileList.length;
					for (var i = 0; i < hasCount; i++) {
						tempFiles.push(files[i]);
					}
					files = tempFiles;
				}
			}
			fileHelper.convertBase64((data) => {
				//转换成功
				//console.log(data);
				if (this.max == 1) this.fileList = [];
				for (var i = 0; i < data.length; i++) {
					this.fileList.push(data[i]);
				}
				this.setValue();

				//自动上传图片
				if (this.sysFileList) {
					this.uploadImages(data);
				}
			}, files, 0);
		},
		handleRemove($index) {
			this.fileList.splice($index, 1);
			this.setValue();
		},

		uploadImages(imgList) {
			//console.log(imgList);
			Promise.all(
				imgList.map((item) => {
					return this.uploadImage(item);
				})
			).then((data) => {
				this.setValue();
				this.showToast("文件上传:" + this.comLan.js.opSuccess, "success");
			}).catch(e => {
				//this.showToast(this.comLan.js.opFail + ":" + e, "error");
			});
		},
		uploadImage(item) {
			//console.log(item)
			return new Promise((resolve, reject) => {
				this.post("api/System/SysFileAdd", {
					SysFileName: item.fileName,
					FilePath: item.base64
				}).then(data => {
					var filePath = data.Result.FilePath;//this.commonUrl(
					item.base64 = filePath;
					resolve(data);
				}).catch(e => {
					reject(e);
				});
			});
		},

		onSuccess(response, file, fileList) {
			if (response.Success == false) {
				this.showToast(response.Message);
				return;
			}
			console.log("onSuccess", response, file);
			var result = response.Result;
			var obj = {
				fileName: result.SysFileName,
				base64: result.FilePath//this.commonUrl(
			}
			if (this.max <= 1) {
				this.fileList = [];
			}
			this.fileList.push(obj);
			// console.log("this.elFileList", this.elFileList);
			// for (var i = 0; i < this.elFileList.length; i++) {
			//     var item = this.elFileList[i];
			//     console.log(item, file)
			//     if (item == file) {
			//         this.elFileList.splice(i, 1);
			//         break;
			//     }
			// }

			this.setValue();

			//全部上传成功才会调用清除clearFiles
			var clear = true;
			//console.log("fileList", fileList);
			for (var i = 0; i < fileList.length; i++) {
				var item = fileList[i];
				//console.log("item", item.percentage, item);
				if (item.percentage != 100) {
					clear = false;
					break;
				}
			}
			if (clear) {
				this.showToast("成功上传文件数:" + fileList.length, "success");
				this.$refs.elUpload.clearFiles();
			}
		},
		exploreFile() {
			this.visible = true;
		}
	},
	created() {
		// console.log("created", this.value);
		this.initFile(this.value, true);
	}
};
</script>
